﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HomeWork
{
    internal class Repository<TEntity, TId> where TEntity : Entity<TId>
    {
        public const int version = 1;
        // 静态只读连接字符串：支持运行时初始化，且初始化后不可修改
        public static readonly string ConnectionString;

        private readonly Dictionary<TId, TEntity> _store = new Dictionary<TId, TEntity>();

        private static Func<TId, TEntity> _entityFactory;



        // 设置实体工厂方法
        public static void SetFactory(Func<TId, TEntity> factory)
        {
            _entityFactory = factory;
        }

        // 添加实体
        public void Add(TEntity entity)
        {
            _store[entity.Id] = entity;
        }

        // 根据Id获取实体
        public TEntity Get(TId id)
        {
            return _store.TryGetValue(id, out var entity) ? entity : null;
        }


        public static TEntity Load(TId id)
        {
            if (_entityFactory == null)
                throw new InvalidOperationException($"Factory not set for {typeof(TEntity).Name}. Call SetFactory first.");

            return _entityFactory(id);
        }


    }


}
